package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.YddCateDto;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台管理
 */
@RestController
@Slf4j
@RequestMapping("index")
public class IndexController {

    @Autowired
    private UserService userService;

    @Autowired
    private ConfigService configService;
    @Autowired
    private YddAdvposService yddAdvposService;
    @Autowired
    private YddTagService yddTagService;
    @Autowired
    private CateService cateService;
    @Autowired
    private YddCateService yddCateService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private YddAdvimgService yddAdvimgService;
    @Autowired
    private YddUserService yddUserService;


    /**
     * 用户登录
     *
     * @param user
     * @return
     */
    @PostMapping("login")
    public ResultData login(@RequestBody User user) {
        log.info("用户信息: 邮箱:{},密码:{}", user.toString());

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getLogin_name, user.getLogin_name());
        queryWrapper.eq(User::getPassword, DigestUtils.md5Hex(user.getPassword()));
        User loginUser = userService.getOne(queryWrapper);

        if (loginUser == null) {
            throw new BusinessException("登录失败!");
        }

        Map retMap = new HashMap();
        Map tokenMap = new HashMap<>();
        // 登录成功
        if (loginUser != null) {
            // 生成token信息
            String roleId = loginUser.getRole_id()
                    .replace("[","")
                    .replace("]", "")
                    .replace("\"", "");

            tokenMap.put("id", loginUser.getId());
            tokenMap.put("roleId", roleId);

            String token = JwtUtils.getToken(tokenMap);
            retMap.put("token", token);

        }
        return ResultData.ok("",retMap);
    }


    /**
     * 获取系统配置
     * @return
     */
    @GetMapping("getConfig")
    public ResultData getConfig() {
        List<Config> list = configService.list();

        Map<String, String> map = new HashMap<>();
        for (Config config : list) {
            map.put(config.getAttr_key(), config.getAttr_value());
        }
        return ResultData.ok("",map);
    }

    /**
     * 获取用户资料
     *
     * @param
     * @return
     */
    @PostMapping("profile")
    public ResultData profile() {
        Map<String, Object> map = configService.profile();
        return ResultData.ok("", map);
    }


    @PostMapping("/logout")
    public void logout() {
        //删除用户信息
        UserHolder.remove();
    }


    /**
     *主页统计信息
     */
    @GetMapping("/baseInfo")
    public ResultData baseInfo() {
        log.info("请求主页统计信息");
        HashMap<String, Object> map = new HashMap<>();
        //广告位数据
        map.put("advpos_num",yddAdvposService.count());
        //tag_num 标签总数
        map.put("tag_num",yddTagService.count());

        //admin_num 管理员总数
        map.put("admin_num",userService.count());

        //article_num 文章总数
        map.put("article_num",articleService.count());

        //cate_num 分类总数
        map.put("cate_num",cateService.count());

        //advimg_num 广告图总数
        map.put("advimg_num",yddAdvimgService.count());
        //最新用户
        LambdaQueryWrapper<YddUser> yddUserWrapper = new LambdaQueryWrapper<>();
        yddUserWrapper.select(YddUser::getId,YddUser::getUsername,YddUser::getSex,YddUser::getIcon,YddUser::getAddress);
        yddUserWrapper.orderByDesc(YddUser::getId);
        Page<YddUser> yddUserPage = new Page<>(1, 7);
        yddUserService.page(yddUserPage, yddUserWrapper);
        List<YddUser> newUsers = yddUserPage.getRecords();
        map.put("new_user",newUsers);

        //热点文章数据
        LambdaQueryWrapper<Article> articleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleLambdaQueryWrapper.select(Article::getId,Article::getTitle,Article::getAuthor,Article::getKeywords,Article::getClick);
        articleLambdaQueryWrapper.orderByDesc(Article::getClick);
        Page<Article> articlePage = new Page<>(1, 7);
        articleService.page(articlePage,articleLambdaQueryWrapper);
        List<Article> articles = articlePage.getRecords();
        map.put("hot_article",articles);

        // user 用户数据
        // 总数和男女分别个数
        Map<String,Object> user = new HashMap<>();

        QueryWrapper<YddUser> wrapper = new QueryWrapper<>();
        wrapper.select("sex,count(sex) as count");
        wrapper.groupBy("sex");
        List<Map<String, Object>> maps = yddUserService.listMaps(wrapper);

        user.put("total",yddUserService.count());
        for (Map<String, Object> usermap : maps) {
            if (usermap.get("sex").equals(1)){
                user.put("user_man",usermap.get("count"));
            }else {
                user.put("user_woman",usermap.get("count"));
            }
        }
        map.put("user",user);

        // all_cate 各类文章分类数据
        //1 先查所有文章类型 cate数据
        LambdaQueryWrapper<YddCate> yddCateWrapper = new LambdaQueryWrapper<>();
        yddCateWrapper.select(YddCate::getId,YddCate::getCatename);
        List<YddCate> yddCates = yddCateService.list(yddCateWrapper);
        //2 根据每个文章id 去查文章表article中对应类型的文章数量
        List<YddCateDto> allCate = yddCates.stream().map((item)->{
            YddCateDto yddCateDto = new YddCateDto();
            BeanUtils.copyProperties(item,yddCateDto);

            LambdaQueryWrapper<Article> tempYddArticleWrapper = new LambdaQueryWrapper<>();
            tempYddArticleWrapper.eq(Article::getCateid,item.getId());

//            yddCateDto.setNum(yddArticleService.list(tempYddArticleWrapper).size());
            yddCateDto.setNum(articleService.count(tempYddArticleWrapper));
            return yddCateDto;
        }).collect(Collectors.toList());
        map.put("all_cate",allCate);
        return ResultData.ok("",map);
       // return "{\"errno\":0,\"errmsg\":\"\",\"data\":{\"all_cate\":[{\"id\":3,\"catename\":\"时政\",\"num\":31},{\"id\":4,\"catename\":\"图片\",\"num\":37},{\"id\":5,\"catename\":\"娱乐\",\"num\":45},{\"id\":6,\"catename\":\"汽车\",\"num\":43},{\"id\":7,\"catename\":\"段子\",\"num\":39},{\"id\":8,\"catename\":\"科技\",\"num\":38},{\"id\":9,\"catename\":\"时尚\",\"num\":23},{\"id\":80,\"catename\":\"动漫\",\"num\":0},{\"id\":969608,\"catename\":\"学习\",\"num\":0},{\"id\":969610,\"catename\":\"学习\",\"num\":2}],\"advpos_num\":7,\"tag_num\":15,\"admin_num\":9,\"article_num\":265,\"cate_num\":10,\"advimg_num\":10,\"new_user\":[{\"id\":196,\"username\":\"1111\",\"sex\":0,\"icon\":\"uploadimages202206171655433115591.png\",\"address\":null},{\"id\":195,\"username\":\"修勾\",\"sex\":0,\"icon\":\"uploadimages202206171655396115559.jpg\",\"address\":null},{\"id\":194,\"username\":\"小可爱\",\"sex\":0,\"icon\":\"uploadimages202206161655376989647.jpeg\",\"address\":null},{\"id\":193,\"username\":\"张三\",\"sex\":0,\"icon\":\"\",\"address\":null},{\"id\":188,\"username\":\"13855143255\",\"sex\":1,\"icon\":null,\"address\":null},{\"id\":187,\"username\":\"13855143240\",\"sex\":1,\"icon\":null,\"address\":null},{\"id\":186,\"username\":\"13855143249\",\"sex\":1,\"icon\":null,\"address\":null}],\"hot_article\":[{\"id\":313,\"title\":\"111111\",\"author\":\"qqqq\",\"keywords\":\"34124324132\",\"click\":111111},{\"id\":174,\"title\":\"李连杰回忆濒临死亡经历：大小便失禁，愿花100万买氧气包\",\"author\":\"落夜\",\"keywords\":\"李连杰\",\"click\":1199},{\"id\":44,\"title\":\"福特全新SUV正式发布，命名“领界”，外形精致，内饰很有档次感！\",\"author\":\"admin\",\"keywords\":\"福特，suv\",\"click\":1192},{\"id\":171,\"title\":\"俄罗斯大学校花，凭借一双长腿，一夜之间爆红网络\",\"author\":\"admin\",\"keywords\":\"大学校花，长腿\",\"click\":1191},{\"id\":228,\"title\":\"菊花什么时候开\",\"author\":\"admin\",\"keywords\":\"菊花 ,，老师 ， 同学 ， 厕所\",\"click\":1191},{\"id\":103,\"title\":\"美元“噩梦”来了？未来或暴跌41%，外汇专家：1欧元可兑2美元！\",\"author\":\"admin\",\"keywords\":\"美元，贬值\",\"click\":1190},{\"id\":85,\"title\":\"奇瑞瑞虎5x新车型官图发布 10月底上市\",\"author\":\"轩辕剑\",\"keywords\":\"新车，上市\",\"click\":1189}],\"user\":{\"total\":151,\"user_man\":76,\"user_woman\":73}}}";

    }


}
